package com.dyrj.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public class GjsjUtils {

    public static void main(String[] args) {
        int Chunk_Size= 5 * 1024; // 5120
        File ifile = new File("D:\\test\\oil-dtu.bin");
        FileInputStream fis;
        String newName;
        FileOutputStream chunk;
        int fileSize = (int) ifile.length();
        int nChunks = 0, read = 0, readLength = Chunk_Size;
        byte[] byteChunk;
        try {
            fis = new FileInputStream(ifile);
            while (fileSize > 0) {
                if (fileSize <= Chunk_Size) {
                    readLength = fileSize;
                }
                byteChunk = new byte[readLength];
                read = fis.read(byteChunk, 0, readLength);

                fileSize -= read;
                nChunks++;
                newName = "D:\\test\\p" + Integer.toString(nChunks)+"_oil-dtu.bin";

                String byte_str = bytesToHex(byteChunk);
                String CheckSum = makeCheckSum(byte_str);
                System.out.println(newName+"_byteToHex:"+byte_str);
                System.out.println(newName+"_checkSum:"+CheckSum);

                chunk = new FileOutputStream(new File(newName));
                chunk.write(byteChunk);
                chunk.flush();
                chunk.close();
                byteChunk = null;
                chunk = null;
            }
            fis.close();
            fis = null;
        }catch(Exception ex){
            ex.printStackTrace();
        }

    }

//    /** 输入十六进制，输出两位校验位 */
//    public static void main(String args[]) {
//        String sHex = "01 F1 00 04 03 06 01 B0";// 输入十六进制
//        sHex = sHex.replace(" ", "");// 去掉中间空格
//        String result = makeCheckSum(sHex);// 计算并获取校验位
//        System.out.println(result);// 输入两位校验位 结果是B0
//    }


    /** 计算校验位 ，返回十六进制校验位 */
    private static String makeCheckSum(String data) {
        int dSum = 0;
        int length = data.length();
        int index = 0;
        // 遍历十六进制，并计算总和
        while (index < length) {
            String s = data.substring(index, index + 2); // 截取2位字符
            dSum += Integer.parseInt(s, 16); // 十六进制转成十进制 , 并计算十进制的总和
            index = index + 2;
        }

        int mod = dSum % 256; // 用256取余，十六进制最大是FF，FF的十进制是255
        String checkSumHex = Integer.toHexString(mod); // 余数转成十六进制
        length = checkSumHex.length();
        if (length < 2) {
            checkSumHex = "0" + checkSumHex;  // 校验位不足两位的，在前面补0
        }
        return checkSumHex;
    }

    /**
     * 字节转十六进制
     * @param b 需要进行转换的byte字节
     * @return  转换后的Hex字符串
     */
    public static String byteToHex(byte b){
        String hex = Integer.toHexString(b & 0xFF);
        if(hex.length() < 2){
            hex = "0" + hex;
        }
        return hex;
    }

    /**
     * 字节数组转16进制
     * @param bytes 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * Hex字符串转byte
     * @param inHex 待转换的Hex字符串
     * @return  转换后的byte
     */
    public static byte hexToByte(String inHex){
        return (byte)Integer.parseInt(inHex,16);
    }

    /**
     * hex字符串转byte数组
     * @param inHex 待转换的Hex字符串
     * @return  转换后的byte数组结果
     */
    public static byte[] hexToByteArray(String inHex){
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1){
            //奇数
            hexlen++;
            result = new byte[(hexlen/2)];
            inHex="0"+inHex;
        }else {
            //偶数
            result = new byte[(hexlen/2)];
        }
        int j=0;
        for (int i = 0; i < hexlen; i+=2){
            result[j]=hexToByte(inHex.substring(i,i+2));
            j++;
        }
        return result;
    }

    public static int getChaifenFiles(String str_filepath, String str_root_path, String filename){
        int Chunk_Size= 5 * 1024; // 5120
//        str_filepath = "D:\\test\\oil-dtu.bin";
//        filename = "oil-dtu.bin";
        File ifile = new File(str_filepath);
        FileInputStream fis;
        String newName;
        FileOutputStream chunk;
        int fileSize = (int) ifile.length();
        int nChunks = 0, read = 0, readLength = Chunk_Size;
        byte[] byteChunk;
        try {
            fis = new FileInputStream(ifile);
            while (fileSize > 0) {
                if (fileSize <= Chunk_Size) {
                    readLength = fileSize;
                }
                byteChunk = new byte[readLength];
                read = fis.read(byteChunk, 0, readLength);

                fileSize -= read;
                nChunks++;
                newName = str_root_path+"\\p" + Integer.toString(nChunks)+"_"+filename;

                String byte_str = bytesToHex(byteChunk);
                String CheckSum = makeCheckSum(byte_str);
                System.out.println(newName+"_byteToHex:"+byte_str);
                System.out.println(newName+"_checkSum:"+CheckSum);

                chunk = new FileOutputStream(new File(newName));
                chunk.write(byteChunk);
                chunk.flush();
                chunk.close();
                byteChunk = null;
                chunk = null;
            }
            fis.close();
            fis = null;
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return nChunks;
    }

    public static Map<String,String> getPackFile(File ifile){
        FileInputStream fis;
        byte[] byteChunk;
        Map<String,String> map_packfile = new HashMap<>();
        try {
            fis = new FileInputStream(ifile);
            byteChunk = new byte[fis.available()];
            fis.read(byteChunk);
            String byte_str = bytesToHex(byteChunk);
            String CheckSum = makeCheckSum(byte_str);
            map_packfile.put("bytetohex",byte_str);
            map_packfile.put("checksum",CheckSum);
            fis.close();
            fis = null;
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return map_packfile;
    }

}
